using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace SD3
{
    public partial class Form1 : Form
    {

        //Load the infopath forms to prepare the controls for use.
        public Form1()
        {
            InitializeComponent();
            formControl1.Open(@"" + Application.StartupPath + @"\forms\BookSubmission\template.xml");
            formControl2.Open(@"" + Application.StartupPath + @"\forms\FeedbackSubmission\template.xml");
            formControl3.Open(@"" + Application.StartupPath + @"\forms\BookSearch\template.xml");
        }

        //When a form is submitted the following methods decide what to do.
        #region Submit

        private void on_Submit1()
        {
            formControl1.XmlForm.SaveAs(@"c:\temp\query_submitType1.txt");
            if (File.Exists("c:\\temp\\query_submitType1_copy.txt"))
            {
                File.Delete("c:\\temp\\query_submitType1_copy.txt");
            }
            File.Copy("c:\\temp\\query_submitType1.txt", "c:\\temp\\query_submitType1_copy.txt");

            // create reader & open file
            TextReader tr = new StreamReader(@"c:\temp\query_submitType1_copy.txt");

            // read a line of text
            post_Data(tr.ReadToEnd(),1);

            // close the stream
            tr.Close();
        }

        private void on_Submit2()
        {
            formControl2.XmlForm.SaveAs(@"c:\temp\a2.txt");
            if (File.Exists("c:\\temp\\b2.txt"))
            {
                File.Delete("c:\\temp\\b2.txt");
            }
            File.Copy("c:\\temp\\a2.txt", "c:\\temp\\b2.txt");

            // create reader & open file
            TextReader tr = new StreamReader(@"c:\temp\b2.txt");

            // read a line of text
            post_Data(tr.ReadToEnd(),2);

            // close the stream
            tr.Close();

        }

        private void on_Submit3()
        {
            formControl3.XmlForm.SaveAs(@"c:\temp\a3.txt");
            if (File.Exists("c:\\temp\\b3.txt"))
            {
                File.Delete("c:\\temp\\b3.txt");
            }
            File.Copy("c:\\temp\\a3.txt", "c:\\temp\\b3.txt");

            // create reader & open file
            TextReader tr = new StreamReader(@"c:\temp\b3.txt");

            // read a line of text
            post_Data(tr.ReadToEnd(),3);

            // close the stream
            tr.Close();
        }

        #endregion

        //Html Posting
        private void post_Data(string postData, int tab)
        {
            try
            {
                // Create a request for the URL.         
                WebRequest request = WebRequest.Create("http://localhost:8080/Catalogue/catalogue");
                // If required by the server, set the credentials.
                request.Credentials = CredentialCache.DefaultCredentials;
                request.ContentType = "application/xml";
                request.Method = "POST";

                //&&&&&&&&&&&&&&&&
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] data = encoding.GetBytes(postData);
                //&&&&&&&&&&&&&&&&&&&

                Stream newStream = request.GetRequestStream();
                newStream.Write(data, 0, data.Length);
                newStream.Close();


                // Get the response.
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                // Display the status.
                textBox1.Text = response.StatusDescription;
                // Get the stream containing content returned by the server.
                Stream dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = reader.ReadToEnd();
                //if we sent a search display it.
                FileStream s = new FileStream("c:\\temp\\rtest.xml", FileMode.Create);
                String output = responseFromServer;
                s.Write(StrToByteArray(output), 0, output.Length);
                s.Close();
                if (tab == 3) tab3_response();
                // Display the content.
                textBox1.Text = responseFromServer;
                // Cleanup the streams and the response.
                reader.Close();
                dataStream.Close();
                response.Close();
                GC.Collect();
            }
            catch(System.Net.WebException webException)
            {
                MessageBox.Show("The following web Exception has occured: " + webException.Message + ". This is often caused by not filling in the form correctly. A stack trace is provided for the application designers below: \n\n " + webException.StackTrace);
            }
            catch(Exception exception)
            {
                MessageBox.Show("The following Exception has occured:\n\n"+exception.Source+"\n The stack trace is provided below: \n\n "+exception.StackTrace);
            }
        }

        //if a button or other gui control is clicked what to do is decided here
        #region GUI Action Handlers

        private void button1_Click(object sender, EventArgs e)
        {
            on_Submit1();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            on_Submit2();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            on_Submit3();
        }

        #endregion

        //if we send a search we want to do something different than normal with the results.
        private void tab3_response()
        {
            FileStream s = new FileStream("c:\\temp\\rtest.xml", FileMode.Open);

            XmlSerializer xmlSerializerObject = new XmlSerializer(typeof(catalogue));
            catalogue catalogueObject = (catalogue)xmlSerializerObject.Deserialize(s);
            drawCatalogue(catalogueObject);
        }

        public void drawCatalogue(catalogue catlogueObject)
        {
            //Clear any controls that have been left over from a previous search results
            panel1.Controls.Clear();

            //foreach book
            int i = 20;
            int j = 1;
            foreach (catalogueBook book in catlogueObject.Items)
            {
                //create the control
                labelTitle = new Label();
                labelTitle.Text = book.title;
                labelTitle.Left = i-10;
                labelTitle.Top = 10;
                labelTitle.Height = 14;
                labelTitle.Width = 100;
                panel1.Controls.Add(labelTitle);

                labelAuthor = new Label();
                labelAuthor.Text = book.author;
                labelAuthor.Left = i;
                labelAuthor.Top = 25;
                labelAuthor.Height = 14;
                labelAuthor.Width = 100;
                panel1.Controls.Add(labelAuthor);


                labelIsbn = new Label();
                labelIsbn.Text = book.isbn;
                labelIsbn.Left = i;
                labelIsbn.Top = 40;
                labelIsbn.Height = 14;
                labelIsbn.Width = 100;
                panel1.Controls.Add(labelIsbn);


                labelRating = new Label();
                labelRating.Text = book.rating;
                labelRating.Left = i;
                labelRating.Top = 55;
                labelRating.Height = 14;
                labelRating.Width = 100;
                panel1.Controls.Add(labelRating);


                labelYear = new Label();
                labelYear.Text = book.year;
                labelYear.Left = i;
                labelYear.Top = 70;
                labelYear.Height = 14;
                labelYear.Width = 100;
                panel1.Controls.Add(labelYear);


                treeControl = new TreeView();


                j = 1;

                if (book.feedback == null)
                {
                    linkLabel = new LinkLabel();
                    linkLabel.Text = "No feed back yet";
                    linkLabel.Left = i-10;
                    linkLabel.Top = 95;
                    linkLabel.Height = 14;
                    linkLabel.Width = 100;
                    panel1.Controls.Add(linkLabel);
                }
                else
                {
                    foreach (catalogueBookFeedback feedbackInst in book.feedback)
                    {
                        
                        nodeProdMaster = new TreeNode();
                        nodeProdMaster.Text = "Feedback" + j.ToString();

                        nodeRating = new TreeNode();
                        nodeRating.Text = feedbackInst.rating;
                        nodeProdMaster.Nodes.Add(nodeRating);

                        nodeComment = new TreeNode();
                        nodeComment.Text = feedbackInst.comment;
                        nodeProdMaster.Nodes.Add(nodeComment);

                        nodeAuthor = new TreeNode();
                        nodeAuthor.Text = feedbackInst.author;
                        nodeProdMaster.Nodes.Add(nodeAuthor);

                        treeControl.Nodes.Add(nodeProdMaster);

                        j++;
                    }
                    treeControl.Left = i;
                    treeControl.Top = 85;
                    panel1.Controls.Add(treeControl);
                }

                i += 220;
            }
        }

        #region utilities

        // C# to convert a string to a byte array.
        public static byte[] StrToByteArray(string str)
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            return encoding.GetBytes(str);
        }

        #endregion

        private System.Windows.Forms.Label labelTitle;
        private System.Windows.Forms.Label labelAuthor;
        private System.Windows.Forms.Label labelIsbn;
        private System.Windows.Forms.Label labelRating;
        private System.Windows.Forms.Label labelYear;
        private System.Windows.Forms.TreeView treeControl;
        private System.Windows.Forms.LinkLabel linkLabel;
        private System.Windows.Forms.TreeNode nodeRating, nodeComment, nodeAuthor, nodeProdMaster;
    }
}